import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { BasicGood } from './data.d';
import { getUserInfo, createCustomer, updateCustomer, approval, entqualification } from './service';
import { message } from 'antd';

const R = require('ramda');

export interface StateType {
  basicGoods: BasicGood[];
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchUserInfo: Effect;
  };
  reducers: {
    show: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'manageEnterpriseMyEnterprise',

  state: {
    userInfo: {},
  },

  effects: {
    *fetchUserInfo({ payload }, { call, put }) {
      const response = yield call(getUserInfo, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'save',
          payload: {
            userInfo: response.content,
          },
        });

        if (payload.onSuccess) payload.onSuccess(response.content);
      }
    },

    *createCustomer({ payload }, { call, put }) {
      const response = yield call(createCustomer, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response.resultCode === 'ok') {
        message.info('创建企业成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },

    *updateCustomer({ payload }, { call, put }) {
      const response = yield call(updateCustomer, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response.resultCode === 'ok') {
        message.info('修改企业信息成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },

    //企业提交审核
    *approval({ payload }, { call, put }) {
      const response = yield call(approval, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response.resultCode === 'ok') {
        message.info('您已提交成功，我们将在1个工作日内安排业务员跟进！！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },

    //企业提交认证

    *entqualification({ payload }, { call, put }) {
      const response = yield call(entqualification, {
        ...R.omit(['onSuccess', 'onFail'])(payload),
      });
      if (response.resultCode === 'ok') {
        message.info('您已提交成功，我们将在1个工作日内安排业务员跟进！！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
